﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Backend.DTO;
using Backend.BLL;

namespace ReSeSSApplication
{
    public partial class PreviousStudies : System.Web.UI.Page
    {
        protected UserDTO loggedInUserDTO = new UserDTO();
        UserBLL aUserBll = new UserBLL();
        StudyBLL aStudyBLL = new StudyBLL();
        PatientBLL aPatientBLL = new PatientBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            AlertError.Visible = false;
            AlertSuccess.Visible = false;
            AlertInfo.Visible = false;

            loggedInUserDTO = (UserDTO)Session["LoggedInUserDTO"];
            RedirectUser(loggedInUserDTO);

            if (!IsPostBack)
            {
                LoadUserListBox();
                LoadPreviousStudiesGridView();
            }
        }

        protected void ShareStudyButton_Click(object sender, EventArgs e)
        {
            try
            {
                int studyId = Convert.ToInt32(ShareStudyIdHiddenField.Value);
                string shareMessage = txtMessage.Text;

                foreach (ListItem item in userListBox.Items)
                {
                    if (item.Selected)
                    {
                        aStudyBLL.ShareStudy(studyId, loggedInUserDTO.Id, Convert.ToInt32(item.Value), shareMessage);
                    }
                }

                AlertSuccess.InnerText = "Study shared successfully.";
                AlertSuccess.Visible = true;
            }
            catch (Exception ex)
            {
                AlertError.InnerText = ex.Message;
                AlertError.Visible = true;
            }
        }

        protected void PreviousStudiesGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    HiddenField studyIdField = (HiddenField)e.Row.FindControl("StudyIdHiddenField");
                    int studyId = Convert.ToInt32(studyIdField.Value);


                    /* build shared popover */
                    int sharedBy = Convert.ToInt32(((HiddenField)e.Row.FindControl("SharedByHiddenField")).Value);
                    string sharedMessage = ((HiddenField)e.Row.FindControl("SharedMessageHiddenField")).Value;
                    UserDTO shareByUser = aUserBll.GetUserById(sharedBy);

                    if (!string.IsNullOrEmpty(sharedMessage))
                    {
                        Label shareUserLabel = (Label)e.Row.FindControl("lblShareUser");
                        shareUserLabel.Attributes.Add("title", "Shared by " + shareByUser.FirstName + " " + shareByUser.LastName);
                        shareUserLabel.Attributes.Add("data-content", sharedMessage);
                    }


                    /* build review and flag text */
                    Label reviewNumberField = (Label)e.Row.FindControl("lblReviewNumber");
                    Label flagNumberField = (Label)e.Row.FindControl("lblFlagNumber");

                    int numberOfPatients = aPatientBLL.GetTotalNumberOfPatients(studyId);
                    int numberOfPatientsReviewed = aPatientBLL.GetTotalNumberOfPatientsReviewed(studyId);
                    int numberOfPatientsFlagged = aPatientBLL.GetTotalNumberOfPatientsFlagged(studyId);

                    if (numberOfPatients <= 0)
                    {
                        reviewNumberField.Text = "No extracted data";
                        flagNumberField.Text = "No extracted data";
                    }
                    else
                    {
                        reviewNumberField.Text = numberOfPatientsReviewed + " out of " + numberOfPatients;

                        if (numberOfPatientsFlagged == 0)
                            flagNumberField.Text = "No flags";
                        else if (numberOfPatientsFlagged == 1)
                            flagNumberField.Text = "1 flag";
                        else
                            flagNumberField.Text = numberOfPatientsFlagged + " flags";
                    }
                }
            }
            catch { }
        }

        protected void PreviousStudiesGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditStudy")
            {
                try
                {
                    Session["StudyId"] = Convert.ToInt32(e.CommandArgument);
                    Session["EditStudy"] = "TRUE";

                    Response.Redirect("NewStudy.aspx");
                }
                catch (Exception ex)
                {
                    AlertError.InnerText = ex.Message;
                    AlertError.Visible = true;
                }
            }
            else if (e.CommandName == "ExtractStudy")
            {
                try
                {
                    int studyId = Convert.ToInt32(e.CommandArgument);
                    int numberExtracted = aPatientBLL.EtractPatients(studyId);

                    AlertSuccess.InnerText = "Successfully extracted patients to the study.";
                    AlertSuccess.Visible = true;
                    LoadPreviousStudiesGridView();
                }
                catch (Exception ex)
                {
                    AlertError.InnerText = ex.Message;
                    AlertError.Visible = true;
                }
            }
            else if (e.CommandName == "ReviewStudy")
            {
                try
                {
                    int studyId = Convert.ToInt32(e.CommandArgument);
                    Session["StudyId"] = studyId;

                    Response.Redirect("ReviewStudy.aspx");
                }
                catch (Exception ex)
                {
                    AlertError.InnerText = ex.Message;
                    AlertError.Visible = true;
                }
            }
            else if (e.CommandName == "DeleteStudy")
            {
                try
                {
                    int studyId = Convert.ToInt32(e.CommandArgument);

                    if (aStudyBLL.DeleteStudy(studyId))
                    {
                        AlertSuccess.InnerText = "Study deleted successfully";
                        AlertSuccess.Visible = true;

                        LoadPreviousStudiesGridView();
                    }
                    else
                    {
                        AlertError.InnerText = "Study delete failed";
                        AlertError.Visible = true;
                    }
                }
                catch (Exception ex)
                {
                    AlertError.InnerText = ex.Message;
                    AlertError.Visible = true;
                }
            }
        }

        protected void PreviousStudiesGridView_RowCreated(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    e.Row.Cells[6].ColumnSpan = 5;
                    e.Row.Cells.RemoveAt(7);
                    e.Row.Cells.RemoveAt(7);
                    e.Row.Cells.RemoveAt(7);
                    e.Row.Cells.RemoveAt(7);
                }
            }
            catch { }
        }

        private void LoadUserListBox()
        {
            userListBox.DataSource = new UserBLL().GetAllUser("User", loggedInUserDTO.Id);
            userListBox.DataTextField = "LoginId";
            userListBox.DataValueField = "Id";
            userListBox.DataBind();
        }

        private void LoadPreviousStudiesGridView()
        {
            List<StudyDTO> listOfStudies = aStudyBLL.GetSavedStudiesByUserId(loggedInUserDTO.Id);
            PreviousStudiesGridView.DataSource = listOfStudies;
            PreviousStudiesGridView.DataBind();
        }

        protected void RedirectUser(UserDTO userDTO)
        {
            if (userDTO != null)
            {
                if (userDTO.UserType == "Administrator")
                {
                    Response.Redirect("AdministratorDashboard.aspx");
                }
            }
            else
            {
                Response.Redirect("Index.aspx");
            }
        }
    }
}